package com.oren.activity.service.impl;

import com.oren.activity.mapper.ActDeploymentMapper;
import com.oren.activity.mapper.ProcessOwnMapper;
import com.oren.activity.pojo.ActDeployment;
import com.oren.activity.pojo.ProcessOwn;
import com.oren.activity.pojo.QueryTask;
import com.oren.activity.service.ProcessOwnService;
import com.oren.base.pojo.Page;
import com.oren.system.mapper.DepartmentMapper;
import com.oren.system.pojo.Department;
import com.oren.util.PageUtil;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wsw
 * @Description:
 * @Date: Create on 2018/8/1 20:44
 */
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class ProcessOwnServiceImpl implements ProcessOwnService {

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private ProcessOwnMapper processOwnMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private ActDeploymentMapper actDeploymentMapper;


    @Override
    public Page<ProcessOwn> pageList(ProcessOwn processOwn, int page, int rows) {
        List<ProcessOwn> list=processOwnMapper.list(processOwn,PageUtil.getBound(page,rows));
        int total=processOwnMapper.count(processOwn);
        return PageUtil.getPageList(list,total);
    }

    @Override
    public int insertEntity(ProcessOwn processOwn, ActDeployment deployment,String username, String userId) {
        int i=0;
        try {
            //开始启动流程
            RuntimeService runtimeService = processEngine.getRuntimeService();
            Map<String, Object> variables = new HashMap<String,Object>();
            variables.put("simpleUser",userId);
            //  runtimeService.startProcessInstanceByKey("myTest2",variables);
            runtimeService.startProcessInstanceById(deployment.getDepId(),variables);

            //完成第一个流程并设置第二个节点的审核人
            TaskService taskService=processEngine.getTaskService();
            Task task=taskService.createTaskQuery().taskCandidateOrAssigned(userId).list().get(0);

            //查询当前用户的领导
            Department department1=departmentMapper.findDepartmentByUserId(Integer.parseInt(userId));
            Map map=new HashMap();
            if(department1!=null && !department1.getUserId().equals(userId)){
                map.put("user1",department1.getUserId());
            }else{
                map.put("user1", departmentMapper.findLeader(department1.getParentId()).getUserId());
            }
            //完成第一步流程并设置第二步的审核人
            taskService.setVariables(task.getId(),map);
            taskService.complete(task.getId());

            processOwn.setExecutionId(task.getExecutionId());
            processOwn.setStatus(2);
            processOwn.setAuditorId(department1.getUserId());
            i=processOwnMapper.insertEntity(processOwn);

        }catch (Exception e){
            e.printStackTrace();
            i=-1;
        }
        return i;
    }

    @Override
    public Page<QueryTask> pageListTask(String userId,int page,int rows) {
        Page<QueryTask> pageList=new Page<QueryTask>();
        List<QueryTask> list=new ArrayList<QueryTask>();

        //运用activity内置的方法，根据userId查询到未审核的相关信息
        TaskService taskService=processEngine.getTaskService();
        List<Task> taskList=taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
        if(taskList!=null && taskList.size()>0){
            for (Task task:taskList) {
                QueryTask queryTask=new QueryTask();
                //查询流程id
                 String pdid=task.getProcessDefinitionId();
                 ProcessOwn processOwn=processOwnMapper.findByPdid(task.getExecutionId());
                queryTask.setProcessName(processOwn.getProcessName());
                queryTask.setApplyId(processOwn.getUserId());
                queryTask.setApplyName(processOwn.getUserName());
                queryTask.setApplyTime(processOwn.getCreateTime());
                queryTask.setProcessDefinitionId(pdid);
                queryTask.setId(processOwn.getId().toString());
                list.add(queryTask);
            }
            pageList.setRows(list);
            pageList.setTotal(taskList.size());
        }else {
            pageList.setRows(list);
            pageList.setTotal(0);
        }
        return pageList;
    }

    @Override
    public void auditor(String id, String userId) {
        //获取这个流程的详细数据
        ProcessOwn processOwn=processOwnMapper.findById(Integer.parseInt(id));

        Map map=new HashMap();

        //Integer auditorId=0;

        //获取当前用户的上一级领导
        Department department1=departmentMapper.findDepartmentByUserId(Integer.parseInt(userId));
        Integer auditorId=departmentMapper.findLeader(department1.getParentId()).getUserId();
        map.put("user2",auditorId);


        TaskService taskService=processEngine.getTaskService();
        //获取当前正在运行的节点信息
        Task task1 = taskService.createTaskQuery().executionId(processOwn.getExecutionId()).singleResult();
        //完成第一个流程并设置第二个节点的审核人
        taskService.setVariables(task1.getId(),map);
        taskService.complete(task1.getId());

        ProcessOwn processOwn1 = new ProcessOwn();
        processOwn1.setId(Integer.parseInt(id));
        //并查询该任务是否完成，
        Task task2 = taskService.createTaskQuery().executionId(processOwn.getExecutionId()).singleResult();
        if(task2!=null){
            processOwn1.setStatus(2);
            processOwn1.setAuditorId(auditorId);
        }else{
            processOwn1.setStatus(3);
            processOwn1.setAuditorId(0);
        }
        //修改数据
        processOwnMapper.updateEntity(processOwn1);
    }
}
